﻿using MeterReader.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MeterReader.Services.Repositories
{
    public class MeterReadRepository : IReadRepository
    {
        private readonly SimMeterDBContext _dbContext;
        private int _offset = 0;

        public MeterReadRepository(SimMeterDBContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 读数据库
        /// </summary>
        /// <param name="callback">读取后的行为</param>
        /// <param name="cancellationToken">终端读取</param>
        /// <returns></returns>
        public async Task ReadDataAsync(Action<TableMeters> callback, CancellationToken cancellationToken)
        {
            _offset++;
            var table = await _dbContext.TMeters!.OrderBy(m => m.ID).Skip(_offset).FirstOrDefaultAsync(cancellationToken);
            if (table != null)
            {
                callback(table);
            }
            else
            {
                _offset = 0;
            }
        }
    }
}